package com.hc.concurrent_likes.quartz;

import com.hc.concurrent_likes.entity.Mood;
import com.hc.concurrent_likes.entity.UserMoodPraiseRel;
import com.hc.concurrent_likes.service.MoodService;
import com.hc.concurrent_likes.service.UserMoodPraiseRelService;
import com.hc.concurrent_likes.utils.ConcurrentLikesConstant;
import com.hc.concurrent_likes.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 描述：定时器
 * @author JXR
 * @date 2022/11/16
 */
@Component
@Configuration
@EnableScheduling
public class PraiseDataSaveDBJob implements ConcurrentLikesConstant {

    private static final Logger LOGGER = LoggerFactory.getLogger(PraiseDataSaveDBJob.class);

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    @Qualifier("userMoodPraiseRelService")
    private UserMoodPraiseRelService userMoodPraiseRelService;

    @Autowired
    @Qualifier("moodService")
    private MoodService moodService;

    /**
     * 被定时调度的任务
     * cron = "0 0/5 * * * *"   ：  从正秒（00）开始，每个5分钟触发一次
     */
    @Scheduled(cron = "0/10 * * * * *")
    public void savePraiseDataToDB2(){

        LOGGER.info(TimeUtils.getCurrentTime() + "将缓存中的数据刷新到数据库中...");

        //在缓存中获取所有被点赞的说说id
        Set<Object> moodIdObjs = redisTemplate.opsForSet().members(PRAISE_HASH_KEY);

        if (CollectionUtils.isEmpty(moodIdObjs)){
            return;
        }

        Set<String> moodIds = new HashSet<>();
        for (Object moodIdObj : moodIdObjs) {
            moodIds.add(moodIdObj.toString());
        }

        for (String moodId : moodIds) {
            //由于一条说说可被多个用户点赞，所以返回的是点赞当前说说的所有用户
            Set<Object> userIdObjs = redisTemplate.opsForSet().members(moodId);
            if(userIdObjs == null || userIdObjs.isEmpty()){
                continue;
            } else {
                Set<String> userIds = new HashSet<>();

                for (Object userIdObj : userIdObjs) {
                    userIds.add(userIdObj.toString());
                }

                if (CollectionUtils.isEmpty(userIds)){
                    continue;
                } else {
                    //循环保存moodId和userId的关联关系到Mysql数据库中
                    for (String userId : userIds) {
                        UserMoodPraiseRel userMoodPraiseRel = new UserMoodPraiseRel();
                        userMoodPraiseRel.setMoodId(moodId);
                        userMoodPraiseRel.setUserId(userId);

                        //保存说说与用户的关联关系
                        userMoodPraiseRelService.save(userMoodPraiseRel);
                    }
                    Mood mood = moodService.findById(moodId);

                    //更新说说的点赞数量
                    mood.setPraiseNum(mood.getPraiseNum() +
                            redisTemplate.opsForSet().size(moodId).intValue());
//                    mood.setPraiseNum(mood.getPraiseNum() +
//                                    (Integer)redisTemplate.opsForValue().get(PRAISE_COUNT_KEY));
                    moodService.update(mood);

                    //清除redis中的数据
                    redisTemplate.delete(moodId);
                }
            }
        }
        //清除缓存数据
        redisTemplate.delete(PRAISE_HASH_KEY);
    }

}
